import { check } from 'meteor/check';
import { Messages } from '/imports/models/Messages';
import { Friends, isFriend } from '/imports/models/Friends';
import { Notifications } from '/imports/models/Notifications';

Meteor.methods({
  makeFriend(friend_id) {
    check(friend_id, String);
    
    Notifications.insert({
      type: 'UserMakeFriend',
      user_id: friend_id,
      details: {
        user_id: Meteor.userId(),
        username: Meteor.user().username,
        avatar: Meteor.user().profile.avatar,
        text: '申请加为好友'
        // 用户[username]申请加为好友
      }
    });
    return true;
  },

  makeFriendSuccess(friend_id, notification_id) {
    check(friend_id, String);

    if (isFriend(Meteor.userId(), friend_id)) {
      Notifications.remove({_id: notification_id});
      return 'is-friend';
    } else {
      Friends.insert({
        user_id: Meteor.userId(),
        friend_id: friend_id
      });
      Friends.insert({
        user_id: friend_id,
        friend_id: Meteor.userId()
      });
      Notifications.remove({_id: notification_id});
      Notifications.insert({
        type: 'UserMakeFriendSuccess',
        user_id: friend_id,
        details: {
          user_id: Meteor.userId(),
          username: Meteor.user().username,
          avatar: Meteor.user().profile.avatar,
          text: '现在是你的好友了，快发私信联系吧'
          // 用户[username]现在是你的好友了，快发私信联系吧
        }
      });
      return true;
    }
  },

  deleteMakeFriendRequest(id) {
    check(id, String);
    return Notifications.remove({_id: id});
  },

  deleteFriend(options) {
    check(options.id, String);

    Friends.remove({
      user_id: Meteor.userId(),
      friend_id: options.id
    });
    Friends.remove({
      user_id: options.id,
      friend_id: Meteor.userId()
    });
    Messages.remove({
      user_id: Meteor.userId(),
      friend_id: options.id
    });
    return true;
  }
});